'use strict';
module.exports = {
	/**
	 * 修改用户所做题目状态
	 * @url client/quest-bank/kh/saveAnswer 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid, answercard, typeId, cate_id } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		let time = new Date().getTime()
		// 遍历
		for (let key in answercard) {
			// 先找之前有没有写过
			let info = await vk.baseDao.findByWhereJson({
				dbName: "q_user_count",
				whereJson: {
					type_id: typeId,
					question_id: key,
					user_id: uid
				}
			})
			// 新增
			if (info == null) {
				await vk.baseDao.add({
					dbName: "q_user_count",
					dataJson: {
						type_id: typeId,
						question_id: key,
						user_id: uid,
						answer: answercard[key].a,
						is_right: answercard[key].r,
						_add_time: time,
						cate_id
					}
				});
			}
			// 修改
			if (info != null) {
				let newInfo = await vk.baseDao.updateById({
					dbName: "q_user_count",
					id: info._id,
					dataJson: {
						type_id: typeId,
						question_id: key,
						user_id: uid,
						answer: answercard[key].a,
						is_right: answercard[key].r,
						_add_time: time,
						_add_time_str: vk.pubfn.timeFormat(time, "yyyy-MM-dd hh:mm:ss"),
					},
				});
			}

			// 错题存储
			if (answercard[key].r == 2) {
				let error = await vk.baseDao.findByWhereJson({
					dbName: "q_user_error",
					whereJson: {
						question_id: key,
						user_id: uid
					}
				})
				// 新增
				if (error == null) {
					await vk.baseDao.add({
						dbName: "q_user_error",
						dataJson: {
							question_id: key,
							user_id: uid
						}
					});
				}
				// 修改
				if (error != null) {
					let newInfo = await vk.baseDao.updateById({
						dbName: "q_user_error",
						id: error._id,
						dataJson: {
							question_id: key,
							user_id: uid
						},
					});
				}
			}
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
